<template>
  <!-- !租客账单 -->
  <div class="room-bill" style="height: 100%">
    <a-card size="small" style="height: 100%" :bodyStyle="{padding:'0'}" v-if="hasOwner" id="cardContent">
      <!-- 租客显示 -->
      <template v-if="currentOwner.id">
        <section id="titleContent" style="padding:10px">
          <a-row type="flex" align="middle" justify="space-between">
            <a-col>
              <a-dropdown v-if="roomOwnerList.length > 1" overlayClassName="hide-scroller-bar" :overlayStyle="{
                height: '500px',
                overflow: 'hidden auto',
                borderRadius: '10px'
              }">
                <div class="owner-name">
                  <a-space>
                    <span>{{ currentOwner.owner_name }}</span>
                    <a-tag v-if="currentOwner.status == 0" color="#87d068">{{ currentOwner.owner_type }}</a-tag>
                    <a-tag v-else color="#777777">{{ currentOwner.owner_type }}</a-tag>
                    <DownOutlined />
                  </a-space>
                </div>
                <template #overlay>
                  <a-menu @click="onRoomOwnerChange" style="border: 1px solid #f0f0f0">
                    <a-menu-item v-for="item of roomOwnerList" :key="item.id">
                      <span>{{ item.owner_name }}</span>
                      <a-tag style="margin-left: 10px;" v-if="item.status == 0" color="#87d068">{{ item.owner_type }}</a-tag>
                      <a-tag style="margin-left: 10px;" v-else color="#777777">{{ item.owner_type }}</a-tag>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <div class="owner-name" v-else>
                <span>{{ currentOwner.owner_name }}</span>
                <a-tag style="margin-left: 10px;" v-if="currentOwner.status == 0" color="#87d068">{{ currentOwner.owner_type }}</a-tag>
                <a-tag style="margin-left: 10px;" v-else color="#777777">{{ currentOwner.owner_type }}</a-tag>
              </div>
            </a-col>
            <a-col>
              <a-button type="link" @click="checkOwnerDetail">
                {{ $L("租客") }}详情
              </a-button>
            </a-col>
          </a-row>
          <a-row type="flex" align="middle" justify="space-between" >
            <a-col class="bill-table-title">
                    <span>账单列表</span>
                    <div class="switch-wrap">
                      <a-switch
                        v-model:checked="isExpandReceived"
                        checked-children="显示"
                        un-checked-children="隐藏"
                        @change="changeShowReceive"
                      />
                      <span style="font-size: 12px; padding: 0 8px">{{
                          isExpandReceived
                              ? "已显示已收账单"
                              : "已隐藏已收账单"
                        }}</span>
                    </div>
                    <div class="switch-wrap">
                      <a-switch
                        v-model:checked="isExpandNotYetDue"
                        checked-children="显示"
                        un-checked-children="隐藏"
                        @change="changeShowNotYetDue"
                      />
                      <span style="font-size: 12px; padding: 0 8px">{{
                          isExpandNotYetDue
                              ? "已显示未到应收期账单"
                              : "已隐藏未到应收期账单"
                        }}</span>
                    </div>
            </a-col>
            <a-col>
                    <a-space>
                      <a-button
                        type="primary"
                        ghost
                        @click="refundVisible = true"
                        v-permission="['billList', 'auth', 'addAdjust']"
                      >
                        退款
                      </a-button>
                      <a-button
                        v-if="selectBillIds.length"
                        type="primary"
                        ghost
                        @click="goMakeCollections"
                      >
                        <template #icon>
                          <CheckCircleOutlined/>
                        </template>
                        组合收款
                      </a-button>

                      <a-button
                        v-permission="['billList', 'auth', 'buildPaymentNotice']"
                        type="primary"
                        ghost
                        @click="addPaymentNotice"
                        v-if="selectBillIds.length"
                      >
                        生成缴费通知单
                      </a-button>

                      <!-- 小区场景特殊处理 -->
                      <template v-if="villageType == 'village'">
                        <a-dropdown>
                          <template #overlay>
                            <a-menu @click="addBillClick">
                              <a-menu-item key="add">手动添加账单</a-menu-item>
                              <a-menu-item key="automatic"
                                >按收费标准生成</a-menu-item
                              >
                            </a-menu>
                          </template>
                          <a-button type="primary">
                            <template #icon>
                              <PlusCircleOutlined />
                            </template>
                            添加账单
                          </a-button>
                        </a-dropdown>
                      </template>
                      <template v-else>
                        <a-button type="primary" @click="addBill()">
                          <template #icon>
                            <PlusCircleOutlined />
                          </template>
                          添加账单
                        </a-button>
                      </template>
                    </a-space>
            </a-col>
          </a-row>
        </section>
        <div class="bill-table hide-scroller-bar" :style="{
                height:`${tableHeight}px`
              }" >
          <a-table
            :dataSource="billList"
            :columns="BILL_COLUMNS"
            :pagination="false"
            rowKey="id"
            :loading="billLoading"
            size="small"
            bordered
            :expandRowByClick="true"
            :customRow="customRow"
            :row-selection="rowSelection"
            :expandedRowKeys="expandedRowKeys"
            @expand="expandRow"
          >
            <template #bodyCell="{ text, record, index, column }">
              <template v-if="column.key === 'receiveOtherTotal'">
                <a-space>
                  <span
                    v-if="record.children"
                    :class="{ 'text-primary': record.otherCount }"
                  >
                    {{ record.otherCount }}项
                  </span>
                  <span> {{ text }} </span>
                  <a-button
                    type="link"
                    v-if="record.children"
                    @click.stop="addBill(record)"
                  >
                    <PlusCircleOutlined />
                  </a-button>
                </a-space>
              </template>
              <template v-if="column.key === 'settleStatus'">
                <template v-if="text.length == 1">
                  <div
                    v-if="text[0] == 5"
                    class="text-error pointer"
                    @click.stop="onMakeCollections(record)"
                  >
                    <span>待收</span>
                    <span
                      v-if="
                        record.children && index == activeTipsIndex
                      "
                    >
                      (点击收款)
                    </span>
                  </div>
                  <div
                    v-if="text[0] == 3"
                    class="text-warning pointer"
                    @click.stop="onMakeCollections(record)"
                  >
                    <span>部分已收</span>
                  </div>
                  <span v-if="text[0] == 2" class="text-success">已收</span>
                  <span v-if="text[0] == 4" class="text-error">待退款</span>
                </template>
                <div
                  v-else
                  class="text-warning pointer"
                  @click.stop="onMakeCollections(record)"
                >
                  <span> 部分已收 </span>
                  <span
                    v-if="
                      record.children && index == activeTipsIndex
                    "
                  >
                    (点击收款)
                  </span>
                </div>
              </template>
              <template v-if="column.key === 'noticeStatus'">
                <span v-if="text" class="text-success">已催收</span>
                <a-space v-else>
                  <span class="text-warning">未催收</span>
                  <a-button
                    type="link"
                    :disabled="
                      record.settleStatus?.length === 1
                        ? record.settleStatus[0] == 2 || record.settleStatus[0] == 4
                        : false
                    "
                    @click.stop="onPayNotice(record)"
                  >
                    <PlusCircleOutlined />
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </div>
      </template>
    </a-card>
    <div class="no-owner" v-else>
      <a-empty description="当前房源暂无账单信息" />
    </div>

    <!-- 租客详情 -->
    <OwnerDetailDrawer
      :visible="ownerDetailVisible"
      :id="currentOwner.id"
      @cancel="onOwnerDetailClose"
    />

    <!-- 账单详情 -->
    <BillDetailDrawer
      :visible="billDetailVisible"
      :id="currentBill.id"
      @cancel="onBillDetailClose"
    />

    <!-- 添加账单 -->
    <NewIncomeBillDrawer
      :visible="addBillVisible"
      :ownerInfo="currentOwner"
      :roomDetail="detail"
      :billCycle="billCycle"
      @cancel="addBillVisible = false"
      @success="onBillAddSuccess"
    />

    <!-- 缴费通知 -->
    <AddPayNotice
      :visible="noticeVisible"
      :ids="billIds"
      @closeDrawer="noticeVisible = false"
      @success="onNoticeSuccess"
    />

    <!-- 发起收款 -->
    <MakeCollections
      :visible="collectVisible"
      :collectionType="collectionType"
      :ownerInfo="currentOwner"
      :roomDetail="detail"
      :billInfo="currentBill"
      :collectionsList="collectionsList"
      @cancel="collectCancel"
      @success="onCollectionsSuccess"
    />

    <!-- 选择收费标准 -->
    <SelectChargeStandard
      :visible="selectStandardVisible"
      :appendParams="{village_id: detail.village_id}"
      @close="chargeStandardClose"
      @success="chargeStandardSuccess"
    />

    <!-- 收费标准生成账单 -->
    <StandardGenerateOrder
      :visible="standardGenerateOrderVisible"
      :standardInfo="currentChargeStandard"
      :charges_id="currentChargeId"
      :roomDetail="detail"
      @close="standardGenerateOrderClose"
    />

    <add-notice
      @closeDrawer="addNoticeClose"
      @success="addNoticeSuccess"
      :visible="addNoticeVisible"
      :ids="addNoticeIds"
    >
    </add-notice>


    <!--  账单退款  -->
    <SelectBillRefundDrawer
      :roomId="detail.id"
      :ownerId="currentOwner.id"
      :visible="refundVisible"
      @handleClose="handleRefundClose"
    />

  </div>
</template>
<script>
import {
  defineComponent,
  reactive,
  toRefs,
  createVNode,
  watch,
  computed,
  nextTick,
  ref,
  watchEffect,
} from "vue";
import {
  PlusOutlined,
  DownOutlined,
  PlusCircleOutlined,
  ExclamationCircleOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  CheckCircleOutlined,
} from "@ant-design/icons-vue";
import OwnerDetailDrawer from "../../../views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
import BillDetailDrawer from "../../../views/bill/BillDetail/modules/BillDetailDrawer.vue";
import NewIncomeBillDrawer from "@/views/bill/NewBill/modules/NewIncomeBillDrawer.vue";
import AddPayNotice from "../../../views/bill/AllBills/AddNotice.vue";
import MakeCollections from "../../../views/bill/NewBill/modules/MakeCollections.vue";
import request from "../../../common/utils/request";
import { useRoute, useRouter } from "vue-router";
import BLCOMMON from "bl-common-vue3";
import { Modal } from "ant-design-vue";
import _ from "lodash";
import utils from "@/common/utils/utils";
import store from "@/store";
import SelectChargeStandard from "../../../views/bill/CashierDesk/modules/SelectChargeStandard.vue";
import StandardGenerateOrder from "../../../views/bill/ChargingStandards/modules/generateOrder.vue";
import moment from "moment";
import AddNotice from "@/views/bill/AllBills/AddNotice.vue";
import SelectBillRefundDrawer from "@/views/bill/AllBills/modules/SelectBillRefundDrawer.vue";
const LANG = {
  owner: BLCOMMON.utils.L("租客"),
};

export default defineComponent({
  name: "RoomBill",
  props: {
    detail: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    AddNotice,
    CheckCircleOutlined,
    ArrowDownOutlined,
    ArrowUpOutlined,
    PlusOutlined,
    DownOutlined,
    PlusCircleOutlined,
    OwnerDetailDrawer,
    NewIncomeBillDrawer,
    AddPayNotice,
    MakeCollections,
    BillDetailDrawer,
    SelectChargeStandard,
    StandardGenerateOrder,
    SelectBillRefundDrawer,
  },
  setup(props, { emit }) {
    const ROUTER = useRouter();
    const ROUTE = useRoute();

    const state = reactive({
      LANG,
      roomOwnerList: [],
      currentOwner: {},
      hasOwner: true,
      ownerDetailVisible: false,
      billList: [],
      billLoading: false,
      addBillVisible: false,
      billCycle: {},
      noticeVisible: false,
      billIds: [],
      collectVisible: false,
      currentBill: {},
      billDetailVisible: false,
      selectedRowKeys: [],
      collectionsList: [], // 收款的list (不包含第几次 且 名称后面加上 期数)
      collectionType: "single", // single 从列表点击 multiple 多选
      isExpandReceived: utils.getStorage("expand_received") === "true", // 已收账单
      isExpandNotYetDue: utils.getStorage("expand_not_yet_Due") === "true", // 未到期账单
      selectStandardVisible: false, //选择收费标准的modal
      standardGenerateOrderVisible: false, //收费标准生成账单的modal
      currentChargeStandard: {}, //当前选中的收费标准
      currentChargeId: 0, //当前选中的收费标准id
      penaltyBill: [], // 罚款账单 （和收银台不同，收银台会有多个楼宇，此处只可能是同一楼宇）
      expandedRowKeys: [],
      allList: [], // 展示全部账单
      notYetDueList: [], // 只隐藏未到期账单
      noReceivedList: [], // 只隐藏已收账单
      noReceivedAndNotYetDue: [], // 隐藏已收账单和未到期账单
      defaultTipIndex: -1, // 默认的tips
      notYetDueTipIndex: -1,  // 只隐藏未到期账单tips
      noReceivedTipIndex: -1,
      noReceivedAndNotYetDueTipIndex: -1,

      tableHeight: 0,  //表格高度
      addNoticeVisible: false,
      addNoticeIds: [], // 生成缴费通知单的账单id
      selectBillIds: [],
      refundVisible: false,
    });

    const villageType = computed(() => store.getters.buildingInfo.villageType);

    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => onBillRowClick(record),
      };
    };

    const onBillRowClick = (record) => {
      console.log("record: ", record);
      if (!record.children) {
        state.billDetailVisible = true;
        state.currentBill = record;
      }
    };

    const expandRow = (e, record) => {
      if (e) {
        state.expandedRowKeys.push(record.id);
      } else {
        state.expandedRowKeys.splice(
          state.expandedRowKeys.indexOf(record.id),
          1
        );
      }
    };

    watch(
      () => ROUTE.name,
      () => {
        state.billDetailVisible = false;
        state.ownerDetailVisible = false;
        emit("close");
      }
    );

    const onBillDetailClose = () => {
      state.billDetailVisible = false;
      state.currentBill = {};
      getRoomOwnerList(true);
    };

    /**收款 */
    const onMakeCollections = (record) => {
      state.collectionType = "single";
      // 始终拿的是第几次的数据
      if (record.children) {
        state.currentBill = record;
      } else {
        state.currentBill = state.billList.find((it) => it.sort == record.sort);
      }
      const billIds = state.currentBill.children.map((it) => it.id);
      request
        .post("/org", "/room/checkRentControlBillMatch", {
          owner_id: state.currentOwner.id,
          room_id: props.detail.id,
          bill_ids: billIds,
        })
        .then(() => {
          state.collectVisible = true;
        })
        .catch((err) => {
          if (err.code == 30024) {
            Modal.confirm({
              title: () => "提示",
              content: () =>
                `该账单日期之前还有账单未支付，可能会发生意想不到的问题，建议您先处理之前的账单。`,
              icon: () => createVNode(ExclamationCircleOutlined),
              centered: true,
              cancelText: "关闭",
              okText: "继续",
              onOk() {
                state.collectVisible = true;
              },
            });
          }
        });
    };

    const collectCancel = () => {
      state.collectVisible = false;
      state.currentBill = {};
      resetMultiple();
    };
    const onCollectionsSuccess = () => {
      collectCancel();
      getBillList();
    };

    /** 缴费通知 */
    const onPayNotice = (record) => {
      if (record.children) {
        state.billIds = record.children.map((item) => item.id);
      } else {
        state.billIds = [record.id];
      }
      state.noticeVisible = true;
    };
    const onNoticeSuccess = () => {
      state.noticeVisible = false;
      resetMultiple();
      getBillList();
    };

    /** 添加收款账单 */
    const addBill = (record) => {
      console.log("record: ", record);
      if (record) {
        state.billCycle = {
          start: record.start,
          end: record.end,
        };
      } else {
        state.billCycle = {};
      }
      state.addBillVisible = true;
    };
    const onBillAddSuccess = () => {
      state.addBillVisible = false;
      resetMultiple();
      getBillList();
    };

    /** 小区场景：添加收款账单下拉菜单 */
    const addBillClick = ({ key }) => {
      if (key == "add") {
        // 手动添加账单
        addBill();
      } else {
        // 按收费标准生成，先弹modal选择收费标准
        state.selectStandardVisible = true;
      }
    };

    const chargeStandardClose = () => {
      state.selectStandardVisible = false;
    };

    const chargeStandardSuccess = (standard) => {
      state.currentChargeStandard = standard;
      state.currentChargeId = standard.id;
      chargeStandardClose();
      state.standardGenerateOrderVisible = true;
    };

    const standardGenerateOrderClose = (isSubmit) => {
      state.standardGenerateOrderVisible = false;
      state.currentChargeId = 0;
      state.currentChargeStandard = {};
      if(isSubmit){
        getBillList()
      }
    };

    /** 查看租客详情 */
    const checkOwnerDetail = () => {
      state.ownerDetailVisible = true;
    };
    const onOwnerDetailClose = () => {
      state.ownerDetailVisible = false;
      getRoomOwnerList(true);
    };

    /** 选中租客 */
    const onRoomOwnerChange = (e, notShrink) => {
      const { key } = e;
      state.currentOwner = state.roomOwnerList.find((it) => it.id == key);
      resetMultiple();
      if (!notShrink) {
        state.expandedRowKeys = [];
      }

      getBillList(true, notShrink);
    };

    /** 获取租客列表 */
    const getRoomOwnerList = (notShrink = false) => {
      request
        .get("/village", "/project/room/getOwnerList", {
          build_id: props.detail.build_id,
          room_id: props.detail.id,
        })
        .then((res) => {
          state.roomOwnerList = [];
          if (res.list && res.list.length > 0) {
            state.hasOwner = true;
            state.roomOwnerList = res.list;
            let index = -1;
            if (state.currentOwner.id) {
              index = state.roomOwnerList.findIndex(
                (it) => it.id == state.currentOwner.id
              );
            }
            if (index == -1) {
              index = 0;
            }
            onRoomOwnerChange({ key: res.list[index].id }, notShrink);
          } else {
            state.hasOwner = false;
          }
        });
    };

    const showModalTips = (msg) => {
      Modal.info({
        title: '请注意：',
        centered: true,
        content: () => msg,
      });
    };

    const resetTipsFilters = () => {
      state.allList = [];
      state.notYetDueList = [];
      state.noReceivedList = [];
      state.noReceivedAndNotYetDue = [];
      state.defaultTipIndex = -1;
      state.notYetDueTipIndex = -1;
      state.noReceivedTipIndex = -1;
      state.noReceivedAndNotYetDueTipIndex = -1;
    };

    const changeBillList = () => {
      if (state.isExpandReceived && state.isExpandNotYetDue) {
        // 展示全部账单
        state.billList = [..._.cloneDeep(state.allList)];
      } else if (state.isExpandReceived && !state.isExpandNotYetDue) {
        // 只隐藏未到期账单
        state.billList = [..._.cloneDeep(state.notYetDueList)];
      } else if (state.isExpandNotYetDue && !state.isExpandReceived) {
        // 只隐藏已收账单
        state.billList = [..._.cloneDeep(state.noReceivedList)];
      } else {
        // 隐藏已收账单和未到期账单
        state.billList = [..._.cloneDeep(state.noReceivedAndNotYetDue)];
      }
    };

    const activeTipsIndex = computed(() => {
      if (state.isExpandReceived && state.isExpandNotYetDue) {
        // 展示全部账单
        return state.defaultTipIndex;
      } else if (state.isExpandReceived && !state.isExpandNotYetDue) {
        // 只隐藏未到期账单
        return state.notYetDueTipIndex;
      } else if (state.isExpandNotYetDue && !state.isExpandReceived) {
        // 只隐藏已收账单
        return state.noReceivedTipIndex;
      } else {
        // 隐藏已收账单和未到期账单
        return state.noReceivedAndNotYetDueTipIndex;
      }
    });

    /** 获取账单列表 */
    const getBillList = (penalty = false, notShrink = false) => {
      state.billLoading = true;
      state.penaltyBill = [];
      if (!notShrink) {
        state.expandedRowKeys = [];
      }
      state.billList = [];
      resetTipsFilters();
      request
        .get("/org", "/owner/ownerFinanceList", {
          owner_id: state.currentOwner.id,
          room_id: props.detail.id,
        })
        .then((res) => {
          nextTick(()=>{
            state.tableHeight = document.getElementById('cardContent').offsetHeight - document.getElementById('titleContent').offsetHeight 
          })
          res.newList.forEach((period, index) => {
            let otherCount = 0;
            let newPeriod = {
              id: `period_${period.sort}`,
              sort: period.sort,
              // 缴费次数、内容
              name: `第${period.sort}次`,
              // 应收时间
              month: period.month,
              // 有效期
              period: `${period.monthStart}~${period.monthEnd}`,
              start: period.monthStart,
              end: period.monthEnd,
              // 应收租金
              receiveRentTotal: Number(period.receiveRentTotal).toFixed(2),
              // 其他费用
              receiveOtherTotal: Number(period.receiveOtherTotal).toFixed(2),
              // 滞纳金
              receiveLatefeeTotal: Number(period.receiveLatefeeTotal).toFixed(
                2
              ),
              // 应收金额
              receiveTotal: utils.countSum([ Number(period.receiveRentTotal), Number(period.receiveOtherTotal),  Number(period.receiveLatefeeTotal), Number(period.outAmountTotal),-Number(period.intoAmountTotal)]).toFixed(2),
              // 收款状态
              settleStatus: period.settleStatusArr,
              // 实收金额
              actualTotal: Number(period.actualTotal).toFixed(2),
              // 催收通知
              noticeStatus: period.noticeFlag,
              // 子账单
              children: period.billList.map((bill) => {
                let newBill = {
                  id: bill.id,
                  fatherId: [`period_${period.sort}`],
                  sort: period.sort,
                  name: bill.cost_type_txt,
                  month: bill.receivable_payment_date,
                  period: `${bill.start_date}~${bill.end_date}`,
                  start: bill.start_date,
                  end: bill.end_date,
                  income_date: bill.income_date,
                  receiveLatefeeTotal: Number(bill.receivable_latefee).toFixed(
                    2
                  ),
                  receiveTotal: utils.countSum([Number(bill.receivable_payment), Number(bill.receivable_latefee), -Number(bill.into_amount), Number(bill.out_amount)]).toFixed(2),
                  noticeStatus: bill.notice_status,
                  settleStatus: [bill.settle_status],
                  actualTotal: (
                    Number(bill.actual_payment) + Number(bill.actual_latefee)
                  ).toFixed(2),
                  build_bind: bill.build_bind,
                  owner_id: bill.owner_id,
                  bill_type: bill.bill_type,
                  cost_type: bill.cost_type,
                  org_id: bill.org_id,
                  remark: bill.remark,
                  is_bond: bill.is_bond,
                  is_forfeit: bill.is_forfeit,
                };
                if (bill.cost_type == "cost_15") {
                  newBill.receiveRentTotal = bill.receivable_payment;
                } else {
                  newBill.receiveOtherTotal = bill.receivable_payment;
                  otherCount++;
                }
                // 罚款账单
                if (
                  newBill.is_forfeit == 1 &&
                    !(
                      newBill.settleStatus?.length === 1 &&
                      (newBill.settleStatus[0] == 2 || newBill.settleStatus[0] == 4)
                    )
                ) {
                  // 非已收的罚款账单映射
                  state.penaltyBill.push({...newBill})
                }
                return newBill;
              }),
            };
            newPeriod.otherCount = otherCount;
            if (
              state.defaultTipIndex < 0 &&
              !(
                newPeriod.settleStatus.length == 1 &&
                (newPeriod.settleStatus[0] == 2 || newPeriod.settleStatus[0] == 4)
              )
            ) {
              state.defaultTipIndex = index;
            }
            // 未收
            if (
              !(
                newPeriod.settleStatus?.length === 1 &&
                (newPeriod.settleStatus[0] == 2 || newPeriod.settleStatus[0] == 4)
              )
            ) {
              state.noReceivedList.push(newPeriod);
              if (state.noReceivedTipIndex < 0) {
                state.noReceivedTipIndex = state.noReceivedList.length - 1;
              }
              // 未收且已到期
              if (moment(newPeriod.month).isBefore(moment().add(1, 'M').format("YYYY-MM"))) {
                state.noReceivedAndNotYetDue.push(newPeriod);
                if (state.noReceivedAndNotYetDueTipIndex < 0) {
                  state.noReceivedAndNotYetDueTipIndex = state.noReceivedAndNotYetDue.length - 1;
                }
              }
            }
            if (moment(newPeriod.month).isBefore(moment().add(1, 'M').format("YYYY-MM"))) {
              state.notYetDueList.push(newPeriod);
              if (state.notYetDueTipIndex < 0) {
                state.notYetDueTipIndex = state.notYetDueList.findIndex((v) => !(v.settleStatus?.length === 1 && (v.settleStatus[0] == 2 || v.settleStatus[0] == 4)))
              }
            }
            // all 展示
            state.allList.push(newPeriod);
          });
          changeBillList();
          if (penalty && state.penaltyBill.length) {
            const selectFine = async (arr) => {
              for (const item of arr) {
                await onSelect(item, true, true);
              }
            }
            selectFine(state.penaltyBill).then(() => {
              if (state.selectedRowKeys.length) {
                showModalTips('当前租客存在罚款账单，已经为您自动选中该账单。')
              }
            })
          }
        })
        .finally(() => {
          state.billLoading = false;
        });
    };

    const resetMultiple = () => {
      state.selectedRowKeys = [];
      state.collectionsList = [];
    };

    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onSelectAll: onSelectAll,
      onSelect: (record, selected) => {onSelect(record, selected, false)},
      getCheckboxProps: getCheckboxProps,
    }));

    // 禁用逻辑
    const isDisabled = (item) => {
      return item.settleStatus?.length === 1
        ? item.settleStatus[0] == 2 || item.settleStatus[0] == 4
        : false;
    };

    const setVal = (list, arr) => {
      list.forEach((v) => {
        if (!isDisabled(v)) {
          arr.push(v.id);
        }
        if (v.children) {
          setVal(v.children, arr);
        }
      });
    };
    /** antd 2.+ 版本不支持 树形表格的父子交互  3+ 版本支持*/
    // 选择所有的时 去除掉禁用的
    const onSelectAll = (selected) => {
      if (selected) {
        let tabData = _.cloneDeep(state.billList);
        const arr = [];
        setVal(tabData, arr);
        state.selectedRowKeys = arr;
      } else {
        state.selectedRowKeys = [];
      }
    };

    // 当用户手动勾选数据行的 Checkbox 时触发的事件
    const onSelect = (record, selected, isFine = false) => {
      const set = new Set(state.selectedRowKeys);
      let tabData = _.cloneDeep(state.billList);
      const id = record.id;
      if (selected) {
        set.add(id);
        record.children && setChildCheck(record.children);
        setParentCheck(id);
      } else {
        set.delete(id);
        record.children && setChildUncheck(record.children);
        setParentUncheck(id);
      }

      state.selectedRowKeys = Array.from(set);
      // 每次选中都把罚款账单勾选
      if (selected && !isFine) {
        if (state.penaltyBill.length) {
          state.penaltyBill.forEach((v) => {
            if (!state.selectedRowKeys.includes(v.id)) {
              onSelect(v, true, true);
            }
          })
        }
      }

      if (isFine) {
        // 罚款账单 默认展开父级
        if (record?.fatherId) {
          let _expandedRow = _.cloneDeep(state.expandedRowKeys);
          record.fatherId.forEach((v) => {
            _expandedRow.push(v);
          })
          state.expandedRowKeys = [...new Set(_expandedRow)]
        }
      }
      // 设置父级选择
      function setParentCheck(id) {
        let childAllHasCheck = false,
          parent = getParent(id);
        if (parent) {
          let childlist = parent.children;
          // 去除掉禁用的
          let noDisChild = childlist.filter((v) => {
            return !isDisabled(v);
          });
          childAllHasCheck = noDisChild.every((v) => {
            return set.has(v.id);
          });
          if (childAllHasCheck) {
            set.add(parent.id);
            setParentCheck(parent.id);
          }
        }
      }
      // 设置父级取消，如果父级的子集有选择，则不取消
      function setParentUncheck(id) {
        let childAllHasCheck = false,
          parent = getParent(id);
        if (parent) {
          let childlist = parent.children;
          // 去除掉禁用的
          let noDisChild = childlist.filter((v) => {
            return !isDisabled(v);
          });
          childAllHasCheck = noDisChild.every((v) => {
            return set.has(v.id);
          });
          if (!childAllHasCheck) {
            set.delete(parent.id);
            setParentUncheck(parent.id);
          }
        }
      }
      // 获取当前对象的父级
      function getParent(id) {
        for (let i = 0; i < tabData.length; i++) {
          if (tabData[i].id === id) {
            return null;
          }
        }
        return _getParent(tabData);
        function _getParent(list) {
          let childlist,
            isExist = false;
          for (let i = 0; i < list.length; i++) {
            if ((childlist = list[i].children)) {
              childlist.forEach(function (v) {
                if (v.id === id) {
                  isExist = true;
                }
              });
              if (isExist) {
                return list[i];
              }
              if (_getParent(childlist)) {
                return _getParent(childlist);
              }
            }
          }
        }
      }
      // 设置child全选
      function setChildCheck(list) {
        list.forEach(function (v) {
          if (!isDisabled(v)) {
            set.add(v.id);
          }
          v.children && setChildCheck(v.children);
        });
      }
      // 设置child取消
      function setChildUncheck(list) {
        list.forEach(function (v) {
          if (!isDisabled(v)) {
            set.delete(v.id);
          }
          v.children && setChildUncheck(v.children);
        });
      }
    };

    const getCheckboxProps = (record) => {
      return {
        disabled: isDisabled(record),
      };
    };

    // 拿到的是所有具体的账单 不包括第几次
    const findBillsByIds = (tree, ids) => {
      let result = [];
      function traverse(node) {
        if (
          ids.includes(node.id) &&
          String(node?.id).indexOf("period_") === -1
        ) {
          let _node = _.cloneDeep(node);
          _node.name = _node.name + `(${_node.period})`;
          result.push(_node);
        }
        if (node?.children?.length) {
          for (const child of node.children) {
            traverse(child);
          }
        }
      }

      for (const node of tree) {
        traverse(node);
      }
      return result;
    };
    const goMakeCollections = () => {
      state.billLoading = true;
      state.collectionType = "multiple";
      state.collectionsList = findBillsByIds(
        state.billList,
        state.selectedRowKeys
      );
      state.billLoading = false;
      state.collectVisible = true;
    };

    const changeShowReceive = (checked) => {
      resetMultiple();
      utils.setStorage("expand_received", checked);
      changeBillList();
    };

    const changeShowNotYetDue = (checked) => {
      resetMultiple();
      utils.setStorage("expand_not_yet_Due", checked);
      changeBillList();
    };

    const addPaymentNotice = () => {
      request
        .post("/org", "/notice/beforeVerify", {
          billIds: state.selectBillIds,
          needMsg: true,
        })
        .then((res) => {
          if (res.data.pass) {
            state.addNoticeIds = res.data.matchIds;
            state.addNoticeVisible = true;
          } else {
            Modal.confirm({
              title: "提示",
              content: () => res.msg,
              icon: () => createVNode(ExclamationCircleOutlined),
              centered: true,
              okText: () => "继续",
              onOk() {
                state.addNoticeIds = res.data.matchIds;
                state.addNoticeVisible = true;
              },
            });
          }
        })
        .catch((err) => {
          console.log(err);
          if (err.code == 60023) {
            Modal.info({
              title: "提示",
              content: () => err.msg,
              centered: true,
              okText: () => "确定",
            });
          }
        });
    };

    const addNoticeClose = () => {
      state.addNoticeVisible = false;
      state.addNoticeIds = [];
    };

    const addNoticeSuccess = () => {
      addNoticeClose();
      resetMultiple();
      getBillList();
    };

    const handleRefundClose = (isSuccess) => {
      state.refundVisible = false;
      if (isSuccess) {
        resetMultiple();
        getBillList();
      }
    };

    watchEffect(() => {
      let bills = findBillsByIds(
        state.billList,
        state.selectedRowKeys
      );
      state.selectBillIds = bills.map((v) => v.id);
    })



    const init = () => {
      getRoomOwnerList();
    };

    init();

    return {
      BILL_COLUMNS,
      ...toRefs(state),
      rowSelection,
      onRoomOwnerChange,
      checkOwnerDetail,
      onOwnerDetailClose,
      addBill,
      onBillAddSuccess,
      onPayNotice,
      onNoticeSuccess,
      onMakeCollections,
      onCollectionsSuccess,
      customRow,
      onBillDetailClose,
      onSelectAll,
      onSelect,
      getCheckboxProps,
      goMakeCollections,
      collectCancel,
      changeShowReceive,
      villageType,
      addBillClick,
      chargeStandardClose,
      chargeStandardSuccess,
      standardGenerateOrderClose,
      expandRow,
      changeShowNotYetDue,
      addNoticeClose,
      addNoticeSuccess,
      addPaymentNotice,
      activeTipsIndex,
      handleRefundClose,
    };
  },
});

const BILL_COLUMNS = [
  {
    title: "缴费次数",
    dataIndex: "name",
  },
  {
    title: "应收时间",
    dataIndex: "month",
    align: "center",
  },
  {
    title: "有效期",
    dataIndex: "period",
    align: "center",
  },
  {
    title: "特殊账单类型",
    dataIndex: "is_forfeit",
    align: "center",
    customRender: ({ text, record, index }) => {
      return text ? '罚金' : '正常';
    },
    width: 105,
  },
  {
    title: "应收租金",
    dataIndex: "receiveRentTotal",
    align: "center",
  },
  {
    title: "其他费用",
    dataIndex: "receiveOtherTotal",
    key: "receiveOtherTotal",
    align: "center",
  },
  {
    title: "滞纳金",
    dataIndex: "receiveLatefeeTotal",
    align: "center",
  },
  {
    title: "应收金额",
    dataIndex: "receiveTotal",
    align: "center",
  },
  {
    title: "收款状态",
    dataIndex: "settleStatus",
    key: "settleStatus",
    align: "center",
  },
  {
    title: "实收金额",
    dataIndex: "actualTotal",
    align: "center",
  },
  {
    title: "催收通知",
    dataIndex: "noticeStatus",
    key: "noticeStatus",
    align: "center",
  },
];
</script>

<style lang="less" scoped>
.no-owner {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.owner-name {
  font-size: 15px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.65);
  display: flex;
  align-items: center;
}

.bill-table {
  padding: 0 10px 10px 10px;
  overflow: hidden auto;
  &:deep(.ant-table) {
    color: rgba(0, 0, 0, 85);
    .ant-table-tbody tr:nth-child(2n) td {
      background-color: initial !important;
    }
  }
  &:deep(.ant-table-row-level-1) {
    font-size: 13px;
    background-color: rgba(0, 0, 0, 0.12) !important;
  }
}

.bill-table-title {
  display: flex;
  align-items: center;
  padding-top: 20px;
}
.switch-wrap {
  background-color: #f2f2f2;
  border-radius: 20px;
  padding: 5px 10px;
  display: flex;
  align-items: center;
  margin-left: 20px;
}
</style>
